package com.code.family.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.code.family.entity.pojo.Accounts;
import com.code.family.entity.pojo.PageParam;
import com.code.family.service.AccountsService;
import com.code.family.utils.ResultVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Optional;

/**
 * 账户管理
 */
@RestController
@RequestMapping("/api/accounts")
@Slf4j
@RequiredArgsConstructor
public class AccountsController {

    private final AccountsService accountsService;

    /**
     * 分页获取账户列表
     */
    @GetMapping
    public ResultVo getList(PageParam param) {
        // 创建LambdaQueryWrapper
        LambdaQueryWrapper<Accounts> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(param.getValue())) {
            queryWrapper.like(Accounts::getAccountName, param.getValue());
        }
        // 创建分页对象
        Page<Accounts> page = new Page<>(Optional.ofNullable(param.getCurrentPage()).orElse(1), param.getPageSize());
        // 执行分页查询
        IPage<Accounts> pageList = accountsService.page(page, queryWrapper);
        // 返回结果
        return ResultVo.success(pageList);
    }

    /**
     * 新增账户
     */
    @PostMapping
    public ResultVo add(@RequestBody Accounts accounts) {
        // 设置创建时间
        accounts.setCreatedAt(new Date());
        // 设置更新时间
        accounts.setUpdatedAt(new Date());
        boolean result = accountsService.addAccount(accounts);
        return ResultVo.success(result);
    }

    /**
     * 修改账户
     */
    @PutMapping
    public ResultVo update(@RequestBody Accounts accounts) {
        // 判断账户是否存在
        if (accountsService.getById(accounts.getId()) == null) {
            return ResultVo.error("账户不存在");
        }
        // 更新时间
        accounts.setUpdatedAt(new Date());
        if (accountsService.updateById(accounts)) {
            return ResultVo.success("修改成功");
        } else {
            return ResultVo.error("修改失败");
        }
    }

    /**
     * 删除账户
     */
    @DeleteMapping("/{id}")
    public ResultVo delete(@PathVariable("id") int id) {
        boolean result = accountsService.deleteAccount(id);
        return ResultVo.success(result);
    }

}
